package com.example.hello.client.Dropdown;

import com.example.hello.BootstrapDropdown;
import com.github.gwtbootstrap.client.ui.constants.IconPosition;
import com.github.gwtbootstrap.client.ui.constants.IconSize;
import com.github.gwtbootstrap.client.ui.constants.IconType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.ComponentConnector;
import com.vaadin.client.ConnectorHierarchyChangeEvent;
import com.vaadin.client.MouseEventDetailsBuilder;
import com.vaadin.client.communication.RpcProxy;
import com.vaadin.client.communication.StateChangeEvent;
import com.vaadin.client.ui.AbstractComponentContainerConnector;
import com.vaadin.shared.Connector;
import com.vaadin.shared.MouseEventDetails;
import com.vaadin.shared.ui.Connect;

@Connect(BootstrapDropdown.class)
public class BootstrapDropdownConnector extends AbstractComponentContainerConnector implements ClickHandler {

    private BootstrapDropdownRpc rpc = RpcProxy.create(BootstrapDropdownRpc.class, this);

    public BootstrapDropdownConnector() {
        getWidget().addClickHandler(this);
    }

    @Override
    protected Widget createWidget() {
        return GWT.create(VBootstrapDropdown.class);
    }

    @Override
    public BootstrapDropdownState getState() {
        return (BootstrapDropdownState) super.getState();
    }

    @Override
    public VBootstrapDropdown getWidget() {
        return (VBootstrapDropdown) super.getWidget();
    }

    @Override
    public void onStateChanged(StateChangeEvent stateChangeEvent) {
        super.onStateChanged(stateChangeEvent);

        BootstrapDropdownState state = getState();

        VBootstrapDropdown dropdown = getWidget();

        for (Connector connector : state.getNavs()) {
            dropdown.add(((ComponentConnector) connector).getWidget());
        }
        dropdown.setBaseIcon(IconType.valueOf(state.getBaseIcon()));
        dropdown.setDropup(state.isDropup());
        dropdown.setIconPosition(IconPosition.valueOf(state.getIconPosition()));
        dropdown.setIconSize(IconSize.valueOf(state.getIconSize()));
        dropdown.setRightDropdown(state.isRightDropdown());
        dropdown.setText(state.getText());
        dropdown.setIcon(IconType.valueOf(state.getType()));
    }

    public void onClick(ClickEvent event) {
        MouseEventDetails details = MouseEventDetailsBuilder.buildMouseEventDetails(
                event.getNativeEvent(), getWidget().getElement());

        rpc.click(details);
    }

    @Override
    public void onConnectorHierarchyChange(ConnectorHierarchyChangeEvent connectorHierarchyChangeEvent) {

    }

    @Override
    public void updateCaption(ComponentConnector connector) {

    }

}